package com.my.app.base;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created by 80002023 on 2016/5/4.
 */
public class JpaSupport<K extends Serializable, V> implements IDao<K, V> {

    @PersistenceContext
    private EntityManager entityManager;

    private Class<V> clazz;

    public JpaSupport() {
        // 在父类中查找子类定义的泛型信息
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        clazz = (Class) pt.getActualTypeArguments()[1];
    }

    public V findById(K id) {
        return entityManager.find(clazz, id);
    }

    public List<V> findAll() {
        return entityManager.createQuery("from " + clazz.getName()).getResultList();
    }

    public void create(V entity) {
        entityManager.persist(entity);
    }

    public V update(V entity) {
        entityManager.merge(entity);
        return entity;
    }

    public void delete(V entity) {
        entityManager.remove(entity);
    }

    public void deleteById(K entityId) {
        entityManager.remove(findById(entityId));
    }

}
